#! /usr/bin/awk -f

#  Important : This software is protected by Copyright and the information
#              contained herein is confidential. Distribution, reproduction
#              as well as exploitation and transmission of its contents is
#              not allowed except if expressly permitted. Infringments
#              result in damage claims.
#              Copyright Wavecom S.A. (c) 2004
# 

# ****************************************************************************
# *  File    : $Workfile$
# *            $Revision$
# *--------------------------------------------------------------------------*
# *                                                                          *
# *  Changes :                                                               *
# $Log$
# ****************************************************************************

# Text File Preprocessor
# Replace {} Templates by values in requested file

BEGIN {
    # Initialize Return Value
    RetVal = 0;
    
    # ARG count must be even
    if ( ARGC % 2 )
    {
        print "Bad arguments count... (" ARGC ")" ;
        RetVal = 1;
        exit 1;
    }
    
    # Init vars
    TemplateNb = 0;
    
    # Get templates and values
    for ( i = 1 ; i < ARGC - 1 ; i++ )
    {
        if ( i % 2 )
        {
            # Template argument
            Template[ TemplateNb ] = ARGV [ i ];
        }
        else
        {
            # Template value
            TemplateValue[ TemplateNb++ ] = ARGV [ i ];
        }
        
        # Forget argument
        ARGV [ i ] = "";
    }
}

{
    # For each line, apply templates
    for ( i = 0 ; i < TemplateNb ; i++ )
    {
        # Split Template on @ char
        NbFields = split ( Template [ i ], TemplateTab, "@" );
        
        # Last element is "match address template"
        # Other Elements are the template to replace
        if ( NbFields > 1 )
        {
            # A match template is present
            TemplateToMatch = TemplateTab [ NbFields ];
            
            # Rebuild template to replace
            TemplateToReplace = "";
            for ( j = 1 ; j < NbFields ; j++ )
            {
                TemplateToReplace = TemplateTab [ j ] "@";
            }
            TemplateToReplace = substr ( TemplateToReplace, 1, length ( TemplateToReplace ) - 1 );
        }
        else
        {
            # Default : match only on the template to replace itself
            TemplateToMatch = TemplateToReplace = Template [ i ];
        }
        
        # Search for template
        if ( match ( $0, TemplateToMatch ) > 0 )
        {
            # Template match, replace
            $0 = gensub( TemplateToReplace, TemplateValue [ i ], "g", $0 );
        }
    }
    
    # Print line !
    print > FILENAME ".tmp";
}

END {
    if ( !RetVal && ( FILENAME != "" ) )
    {
        # Replace original file by processed one
        system ( "mv " FILENAME ".tmp " FILENAME );
    }
    
    exit RetVal;
}
